package com.yjt.sousou.main;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.yjt.sousou.Api;
import com.yjt.sousou.R;
import com.yjt.sousou.base.BaseFragment;
import com.yjt.sousou.create.entity.Department;
import com.yjt.sousou.create.entity.Location;
import com.yjt.sousou.detail.CommonPop;
import com.yjt.sousou.detail.entity.FilterBean;
import com.yjt.sousou.http.DialogCallback;
import com.yjt.sousou.main.entity.OrderFilterBean;
import com.yjt.sousou.utils.GetTimeUtil;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者：83734
 * 时间：2018/11/22
 * 描述：
 */
public class OrderFilterFragment extends BaseFragment {
    @BindView(R.id.tv_has_parts)
    TextView mTvHasParts;
    private String timeStart = "";
    private String timeEnd = "";
    @BindView(R.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R.id.tv_location)
    TextView mTvLocation;
    @BindView(R.id.tv_department)
    TextView mTvDepartment;
    @BindView(R.id.rl_main)
    RelativeLayout mRlMain;
    private List<TextView> mTextViews = new ArrayList<>();
    private List<Location.DataBean> mAreas = new ArrayList<>();
    private List<Location.DataBean.DidianListsBean> mPlaces = new ArrayList<>();
    private List<FilterBean> mDepartments = new ArrayList<>();
    private String departmentId = "";
    private String groupIds = "";
    private String placeId = "";
    private String areaId = "";
    private String placeName = "";
    private String areaName = "";
    private String isParts = "";//是否有配件
    protected PopupWindow mPop;

    public static OrderFilterFragment newInstance() {
        OrderFilterFragment newestFragment = new OrderFilterFragment();
        Bundle bundle = new Bundle();
        newestFragment.setArguments(bundle);
        return newestFragment;
    }

    @Override
    protected Object setLayoutId() {
        return R.layout.fragment_order_filter;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        TextView tv_this_year = view.findViewById(R.id.tv_this_year);
        TextView tv_this_month = view.findViewById(R.id.tv_this_month);
        TextView tv_seven_day = view.findViewById(R.id.tv_seven_day);
        TextView tv_today = view.findViewById(R.id.tv_today);
        mTextViews.add(tv_this_year);
        mTextViews.add(tv_this_month);
        mTextViews.add(tv_seven_day);
        mTextViews.add(tv_today);
        initData();
    }

    @Override
    protected void onFirstVisible() {
        super.onFirstVisible();
    }

    private void initData() {
        OkGo.<Department>get(Api.get().getDepartment())
                .tag(this)
                .execute(new DialogCallback<Department>(Department.class, getActivityContext()) {
                    @Override
                    public void onSuccess(Response<Department> response) {
                        Department body = response.body();
                        for (Department.DataBean data : body.getData()) {
                            mDepartments.add(new FilterBean(data.getId(), data.getBumen()));
                        }
                    }
                });
        OkGo.<Location>get(Api.get().getLocation())
                .tag(this)
                .execute(new DialogCallback<Location>(Location.class, getActivityContext()) {
                    @Override
                    public void onSuccess(Response<Location> response) {
                        Location location = response.body();
                        if (location != null && location.getData().size() != 0) {
                            mAreas.addAll(location.getData());
                        }
                    }
                });
    }

    @OnClick({R.id.tv_this_year, R.id.tv_this_month, R.id.tv_seven_day, R.id.tv_today, R.id.tv_start_time, R.id.tv_end_time, R.id.tv_location, R.id.tv_department
            , R.id.btn_reset, R.id.btn_confirm,R.id.tv_has_parts})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_this_year:
                getTime(0);
                setState(mTextViews, 0);
                break;
            case R.id.tv_this_month:
                getTime(1);
                setState(mTextViews, 1);
                break;
            case R.id.tv_seven_day:
                getTime(2);
                setState(mTextViews, 2);
                break;
            case R.id.tv_today:
                getTime(3);
                setState(mTextViews, 3);
                break;
            case R.id.tv_start_time:
                selectTime(1);
                break;
            case R.id.tv_end_time:
                selectTime(2);
                break;
            case R.id.tv_location:
                showPlacePop();
                makeWindowDark();
                break;
            case R.id.tv_department:
                CommonPop departmentPop = new CommonPop(getActivityContext(), mDepartments, new CommonPop.ResultListener() {
                    @Override
                    public void res(String id, String name) {
                        departmentId = id;
                        mTvDepartment.setText(name);
                        LogUtils.i("departmentid", departmentId);
                    }

                    @Override
                    public void dismiss() {
                        makeWindowLight();
                    }
                });
                departmentPop.show(mRlMain);
                makeWindowDark();
                break;
            case R.id.btn_reset:
                reset();
                break;
            case R.id.btn_confirm:
                OrderFilterBean filterBean = new OrderFilterBean(timeStart, timeEnd, areaId,
                        placeId, departmentId, groupIds,isParts);
                int currentIndex = ((MainActivity) getActivity()).getCurrentIndex();
                filterBean.setFrom(currentIndex);
                EventBus.getDefault().post(filterBean);
                break;
            case R.id.tv_has_parts:
                isParts = TextUtils.isEmpty(isParts)? "1":"";
                if(!TextUtils.isEmpty(isParts)){
                    mTvHasParts.setBackgroundResource(R.drawable.login_btn_bg);
                    mTvHasParts.setTextColor(ContextCompat.getColor(getActivityContext(),R.color.white));
                }else {
                    mTvHasParts.setBackgroundResource(R.drawable.work_state_out_bg);
                    mTvHasParts.setTextColor(ContextCompat.getColor(getActivityContext(),R.color.gray_text));
                }
                break;
            default:
        }
    }

    private void reset() {
        timeStart = "";
        timeEnd = "";
        placeId = "";
        placeName = "";
        areaName = "";
        areaId = "";
        departmentId = "";
        groupIds = "";
        isParts = "";
        mTvDepartment.setText("全部");
        mTvLocation.setText("全部");
    }

    private void selectTime(final int position) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        final DatePickerDialog mDialog = new DatePickerDialog(getActivityContext(), DatePickerDialog.THEME_DEVICE_DEFAULT_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String date = year + "." + (monthOfYear + 1) + "." + dayOfMonth;
                String date1 = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                try {
                    if (position == 1) {
                        mTvStartTime.setText(date);
                        timeStart = GetTimeUtil.ymd2Timestamp1(date1);
                    } else {
                        mTvEndTime.setText(date);
                        timeEnd = GetTimeUtil.ymd2Timestamp1(date1);
                    }
                    setState(mTextViews, 4);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }, year, month, day);
        mDialog.show();
    }

    private void getTime(int position) {
        long nowStamp = System.currentTimeMillis();
        switch (position) {
            case 0:
                String ymd1 = GetTimeUtil.getYMDTime1(nowStamp);
                String ymdhms1 = ymd1.substring(0, ymd1.indexOf("/") + 1) + "1/1 00/00/00";
                String setText1 = ymd1.substring(0, ymd1.indexOf("/") + 1) + "01/01";
                setText1 = setText1.replace("/", ".");
                String start5 = "";
                try {
                    start5 = GetTimeUtil.ymdhms2Timestamp(ymdhms1);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                String end5 = GetTimeUtil.getEndTime(nowStamp);
                setValue(String.valueOf(start5), String.valueOf(end5), setText1);
                break;
            case 1:
                String ymd = GetTimeUtil.getYMDTime1(nowStamp);
                String ymdhms = ymd.substring(0, ymd.lastIndexOf("/") + 1) + "1 00/00/00";
                String setText2 = ymd.substring(0, ymd.lastIndexOf("/") + 1) + "01";
                setText2 = setText2.replace("/", ".");
                String start4 = "";
                try {
                    start4 = GetTimeUtil.ymdhms2Timestamp(ymdhms);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                String end4 = GetTimeUtil.getEndTime(nowStamp);
                setValue(String.valueOf(start4), String.valueOf(end4), setText2);
                break;
            case 2:
                String start3 = GetTimeUtil.getStartTime(nowStamp - (6 * 24 * 60 * 60 * 1000));
                String setText3 = GetTimeUtil.getYMDTimeD(nowStamp - (6 * 24 * 60 * 60 * 1000));
                String end3 = GetTimeUtil.getEndTime(nowStamp);
                setValue(String.valueOf(start3), String.valueOf(end3), setText3);
                break;
            case 3:
                String start1 = GetTimeUtil.getStartTime(nowStamp);
                String setText4 = GetTimeUtil.getYMDTimeD(nowStamp);
                String end1 = GetTimeUtil.getEndTime(nowStamp);
                setValue(String.valueOf(start1), String.valueOf(end1), setText4);
                break;
            default:
        }
    }

    private void setValue(String startTime, String endTime, String startStr) {
        timeStart = startTime;
        timeEnd = endTime;
        mTvStartTime.setText(startStr);
        String endStr = GetTimeUtil.getYMDTimeD(System.currentTimeMillis());
        mTvEndTime.setText(endStr);
    }

    //选择位置
    private void showPlacePop() {
        View view = LayoutInflater.from(getActivityContext()).inflate(R.layout.pop_select_place, null);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        RecyclerView rvLeft = view.findViewById(R.id.rl_place_1);
        LinearLayoutManager managerL = new LinearLayoutManager(getActivityContext());
        managerL.setOrientation(LinearLayoutManager.VERTICAL);
        rvLeft.setLayoutManager(managerL);
        RecyclerView rvRight = view.findViewById(R.id.rl_place_2);
        LinearLayoutManager managerR = new LinearLayoutManager(getActivityContext());
        managerR.setOrientation(LinearLayoutManager.VERTICAL);
        rvRight.setLayoutManager(managerR);
        final BaseQuickAdapter leftAdapter = new BaseQuickAdapter<Location.DataBean, BaseViewHolder>(R.layout.item_my_pop_list, mAreas) {
            @Override
            protected void convert(BaseViewHolder helper, Location.DataBean item) {
                helper.setText(R.id.tv_name, item.getQuyu());
                if (item.isClicked()) {
                    helper.setTextColor(R.id.tv_name, ContextCompat.getColor(getActivityContext(), R.color.text_color));
                    helper.setBackgroundRes(R.id.rl_item, R.color.gray);
                } else {
                    helper.setTextColor(R.id.tv_name, ContextCompat.getColor(getActivityContext(), R.color.black));
                    helper.setBackgroundRes(R.id.rl_item, R.color.white);
                }
            }
        };
        final BaseQuickAdapter rightAdapter = new BaseQuickAdapter<Location.DataBean.DidianListsBean, BaseViewHolder>(R.layout.item_my_pop_list, mPlaces) {
            @Override
            protected void convert(BaseViewHolder helper, Location.DataBean.DidianListsBean item) {
                helper.setText(R.id.tv_name, item.getDidian_name());
                if (item.isClicked()) {
                    helper.setTextColor(R.id.tv_name, ContextCompat.getColor(getActivityContext(), R.color.text_color));
                    helper.setBackgroundRes(R.id.rl_item, R.color.gray);
                } else {
                    helper.setTextColor(R.id.tv_name, ContextCompat.getColor(getActivityContext(), R.color.black));
                    helper.setBackgroundRes(R.id.rl_item, R.color.white);
                }
            }
        };
        leftAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<Location.DataBean> data = leftAdapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setClicked(position == i);
                }
                mPlaces.clear();
                mPlaces.addAll(data.get(position).getDidian_lists());
                placeId = "";
                placeName = "";
                areaId = data.get(position).getId();
                rightAdapter.notifyDataSetChanged();
                leftAdapter.notifyDataSetChanged();
                areaName = data.get(position).getQuyu();
            }
        });
        rvLeft.setAdapter(leftAdapter);

        rightAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<Location.DataBean.DidianListsBean> data = rightAdapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setClicked(position == i);
                }
                placeId = data.get(position).getDidian_id();
                rightAdapter.notifyDataSetChanged();
                placeName = data.get(position).getDidian_name();
                LogUtils.i("placeId", placeId);
            }
        });
        rvRight.setAdapter(rightAdapter);

        mPop = new PopupWindow(view, 5 * mScreenWidth / 6, 2 * mScreenWidth / 3, true);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                makeWindowLight();
            }
        });
        mPop.showAtLocation(mRlMain, Gravity.CENTER, 0, 0);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvLocation.setText(areaName + "-" + placeName);
                mPop.dismiss();
            }
        });
    }
}
